<?php
/**
 * #Celebrate Shieh
 *             ,%%%%%%%%,
 *           ,%%/\%%%%/\%%
 *          ,%%%\c "" J/%%%
 * %.       %%%%/ o  o \%%%
 * `%%.     %%%%    _  |%%%
 *  `%%     `%%%%(__Y__)%%'
 *  //       ;%%%%`\-/%%%'
 * ((       /  `%%%%%%%'
 *  \\    .'          |
 *   \\  /       \  | |
 *    \\/         ) | |
 *     \         /_ | |__
 *     (___________))))))) 攻城湿
 *
 *        _       _
 * __   _(_)_   _(_) __ _ _ __
 * \ \ / / \ \ / / |/ _` |'_ \
 *  \ V /| |\ V /| | (_| | | | |
 *   \_/ |_| \_/ |_|\__,_|_| |_|
 */

namespace App\Services;

use App\Models\System\Info;
use App\Models\System\Role;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;

class UserService
{

    use Service;

    /**
     * 用户首页
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function UserIndexService( $request )
    {
        $where  = function ( $query ) use ( $request ) {
            $query->where('is_show', 1);
            if ( $request->filled('name') and $request->input('name') != '' ) $query->where('name', $request->input('name'));
            if ( $request->filled('static') and $request->input('static') != '-1' ) $query->where('static', $request->input('static'));
            $query->where('status', 1);
        };
        $select = [ 'id', 'name', 'email', 'phone', 'is_show', 'static', 'created_at' ];
        $with   = [
            'info' => function ( $query ) {
                $query->select('id', 'uid', 'rename', 'avatar', 'content');
            },
        ];
        return User::PaginateModel($where, $with, $select);
    }

    /**
     * 用户新增页
     *
     * @return Role[]|\Illuminate\Database\Eloquent\Collection
     */
    public function UserCreateService()
    {
        $select = [ 'id', 'name' ];
        return Role::AllModel($select);
    }

    /**
     * 用户添加
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function UserStoreService( $request )
    {
        if ( $request->input('role_id') ) {
            $role = User::FindPluckModel(Auth::id(), 'name');//获取用户所有权限
            $top  = '超级管理员';
            foreach ( $role as $key => $value ) if ( $value != $top ) foreach ( $request->input('role_id') as $v ) if ( Role::ValueModel($v, 'name') == $top ) return back()->with('error', $this->getErrorCode()::message(1027));
        }
        $validator = $this->getAdminValidator()->UserStoreValidator($request);
        if ( $validator->first() ) return back()->with('error', $validator->first());
        if ( ! $json = Cookie::get('username_' . $request->input('submit')) ) return back()->with('error', $this->getErrorCode()::message(1030));
        $code = explode(',', $json);
        if ( $request->input('code') != $code[ 0 ] || Auth::id() != $code[ 2 ] ) return back()->with('error', $this->getErrorCode()::message(1021));
        if ( $request->input('email') != $code[ 1 ] ) return back()->with('error', $this->getErrorCode()::message(1022));
        $data[ 'name' ]     = $request->input('name');
        $data[ 'email' ]    = $request->input('email');
        $data[ 'password' ] = bcrypt($request->input('password', 123456));//加密
        $data[ 'phone' ]    = $request->input('phone');
        DB::transaction(function () use ( $request, $data ) {
            $user = User::CreateModel($data);
            $user->roles()->sync($request->input('role_id'));//更改权限
            $data1[ 'uid' ] = $user->id;
            Info::CreateModel($data1);
        });
        return back()->with('success', $this->getErrorCode()::message(209));
    }

    /**
     * 编辑用户
     *
     * @param $id
     *
     * @return mixed
     */
    public function UserEditService( $id )
    {
        $user       = User::FindModel($id, [], [ 'id', 'name', 'phone', 'email' ]);
        $roles      = Role::AllModel([ 'id', 'name' ]);
        $user_roles = $user->roles->pluck('id');//获取用户的所有权限
        return view('system.user.edit', compact('user', 'roles', 'user_roles'));
    }

    /**
     * 更新用户
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function UserUpdateService( $request )
    {
        $user = User::FindModel($request->input('id'), [], [ 'id', 'email', 'phone', 'password' ]);
        if ( $request->input('role_id') ) {
            $role = User::FindPluckModel(Auth::id(), 'name');//获取用户的所有权限
            $top  = '超级管理员';
            foreach ( $role as $key => $value ) if ( $value != $top ) foreach ( $request->input('role_id') as $v ) if ( Role::ValueModel($v, 'name') == $top ) return back()->with('error', $this->getErrorCode()::message(1027));
        }
        $validator = $this->getAdminValidator()->UserUpdateEmailValidator($request);
        if ( $validator->first() ) return back()->with('error', $validator->first());
        if ( $request->input('email') != $user->email ) {
            if ( ! $json = Cookie::get('username_' . $request->input('submit')) ) return back()->with('error', $this->getErrorCode()::message(1030));
            $code = explode(',', $json);
            if ( $request->input('code') != $code[ 0 ] || Auth::id() != $code[ 2 ] ) return back()->with('error', $this->getErrorCode()::message(1021));
            if ( $request->input('email') != $code[ 1 ] ) return back()->with('error', $this->getErrorCode()::message(1022));
        }
        $data[ 'email' ] = $request->input('email');
        if ( $request->filled('password') ) $data[ 'password' ] = bcrypt($request->input('password'));
        $data[ 'phone' ] = $request->input('phone');
        DB::transaction(function () use ( $request, $user, $data ) {
            $user->update($data);
            $user->roles()->sync($request->input('role_id'));//更改权限
            $data1[ 'uid' ] = $user->id;
            Info::UpdateModel($request->input('id'), $data1);
        });
        return back()->with('success', $this->getErrorCode()::message(203));
    }

    /**
     * 删除用户
     *
     * @param $id
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function UserDestroyService( $id )
    {
        if ( $id == Auth::id() ) return back()->with('error', $this->getErrorCode()::message(1028));
        $role = User::FindPluckModel($id, 'name');//获取用户的所有权限
        $top  = '超级管理员';
        foreach ( $role as $key => $value ) if ( $value == $top ) return back()->with('error', $this->getErrorCode()::message(1026));
        $user         = User::FindModel($id, [], [ 'id', 'static' ]);
        $user->static = 2;
        $user->save();
        return back()->with('success', $this->getErrorCode()::message(204));
    }

    /**
     * 批量删除用户
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function UserDeleteService( $request )
    {
        $top    = '超级管理员';
        $result = DB::transaction(function () use ( $request, $top ) {
            $ids = $request->input('id');
            foreach ( $ids as $value ) {
                if ( $value == Auth::id() ) return message($this->getErrorCode()::message(1028));
                $role = User::FindPluckModel($value, 'name');//获取用户的所有权限列表
                foreach ( $role as $key => $v ) if ( $v == $top ) return message($this->getErrorCode()::message(1026));
                $user         = User::FindModel($value, [], [ 'id', 'static' ]);
                $user->static = 2;
                $user->save();
            }
            return data();
        });
        return $result;
    }

    /**
     * 修改用户状态
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function UserStatusService( $request )
    {
        if ( $request->input('id') == Auth::id() ) return message($this->getErrorCode()::message(1028));
        $role = User::FindPluckModel($request->input('id'), 'name');//获取用户的所有权限
        $top  = '超级管理员';
        foreach ( $role as $key => $value ) if ( $value == $top ) return message($this->getErrorCode()::message(1026));
        $data[ 'static' ] = $request->input('static') == 1 ? 2 : 1;//三元判断 用户的状态
        $where            = function ( $query ) use ( $request ) {
            $query->where('id', $request->input('id'));
            $query->where('is_show', 1);
        };
        User::UpdateModel($where, $data);
        return data();
    }
}
